package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.AddressBook;
import com.itheima.reggie.service.AddressBookService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/addressBook")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    //新增地址
    @PostMapping
    public R<String> add(@RequestBody AddressBook addressBook){
        Long userId = BaseContext.getCurrentId();
        addressBook.setUserId(userId);
        addressBookService.save(addressBook);
        return R.success("保存地址成功");
    }

    //设置默认地址
    @PutMapping("/default")
    public R<String> setdefault(@RequestBody AddressBook addressBook){
        LambdaUpdateWrapper<AddressBook> luw = new LambdaUpdateWrapper<>();
        luw.set(AddressBook::getIsDefault,0);
        luw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        addressBookService.update(luw);

        addressBook.setIsDefault(1);
        addressBookService.updateById(addressBook);
        return R.success("设置成功");
    }

    //查询所有地址
    @GetMapping("/list")
    public R<List<AddressBook>> getlist(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        List<AddressBook> list = addressBookService.list(lqw);
        return R.success(list);

    }

    //根据id查询地址
    @GetMapping("/{id}")
    public R<AddressBook> getById(@PathVariable Long id){
        //AddressBook addressBook = addressBookService.getById(id);
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getId,id);

        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);
    }

    //查询默认地址
    @GetMapping("/default")
    public R<AddressBook> getDefault(){
        LambdaQueryWrapper<AddressBook> lqw = new LambdaQueryWrapper<>();
        lqw.eq(AddressBook::getIsDefault,1);
        lqw.eq(AddressBook::getUserId,BaseContext.getCurrentId());
        AddressBook one = addressBookService.getOne(lqw);
        return R.success(one);
    }

    //删除地址
    @DeleteMapping
    public R<String> deletedByIds(@RequestParam List<Long> ids){

        addressBookService.removeByIds(ids);
        return R.success("删除成功");
    }

    //修改地址
    @PutMapping
    public R<String> updateAddress(@RequestBody AddressBook addressBook){
        addressBookService.updateById(addressBook);
        return R.success("修改成功");
    }
}
